
// var a123=004;
//网络请求
function request(url, success, complete, fail, method = "GET", header = {}) {
  wx.showToast({
    title: '加载中....',
    icon: 'loading',
    duration: 1000
  });
  wx.request({
    url: url,
    data: {},
    method: method, // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    header: header ? header : "application/json", // 设置请求的 header
    success: function (res) {
      var jsonString = res.data;
      if (typeof (jsonString) == 'string') {
        jsonString = jsonString.substring(jsonString.indexOf("{"), jsonString.lastIndexOf("}") + 1);
        res.data = JSON.parse(jsonString);
      }
      success(res);
    },
    fail: function (e) {
      fail(e);

      // fail
    },
    complete: function (e) {
      complete(e);
      // complete
    },

  })
}
//验证手机
function inputRole(value, regexp) {
  if (regexp.test(value) == true) {
    return true;
  } else {
    return false;
  }
}

function time(date1, date2) {
  var oDate1 = new Date(date1);
  var oDate2 = new Date(date2);
  if (oDate1.getTime() > oDate2.getTime()) {
    return false;
  } else {
    return true;
  }
}


function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()
  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

module.exports = {
  request: request,
  //这边这个是新添加的方法
  getOpenID: getOpenID,
  getRequest: getRequest,
  postRequest: postRequest,
  getUserInfo: getUserInfo,
  hiddenShare: hiddenShare,
  formatTime: formatTime,
  formatNumber: formatNumber,
  inputRole: inputRole,
  showModal: showModal,
  showModal2: showModal2,
  waiton: waiton,
  collectRequest: collectRequest
}

/**
 * 获取openid
 */
var appid = 'wx2647b65c2027ecaf';
var secret = '72373674b396bb5eff6b6b33b603c097';

function getOpenID(success, flag = false) {
  var openid = wx.getStorageSync('openid')
  var user = wx.getStorageSync('user');
  var session_key = wx.getStorageSync('session');
  if (flag == false) {
    showLoading();
  }
  if (!user) {
    getUserInfo(success);
  } else {
    openid(success);
  }
}
function openid(success) {
  var openid = wx.getStorageSync('openid')
  var session = wx.getStorageSync('session');
  if (openid) {
    var parmars = {
      openid: openid,
      session_key: session
    }
    success(parmars);
  } else {
    wx.login({
      success: function (res) {
        if (res.code) {
          var par = {
            code: res.code
          };
          wx.request({
            url: 'https://ceshi.cadhx.com/api/apiregister/get_openid',
            data: par,
            method: "POST",
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            success: function (res) {
              var jsonString = res.data.data; //坑,不能是字符串
              if (typeof (jsonString) == 'string') {
                jsonString = jsonString.substring(jsonString.indexOf("{"), jsonString.lastIndexOf("}") + 1);
                res.data.data = JSON.parse(jsonString);
              }
              wx.setStorage({
                key: "openid",
                data: res.data.data.openid
              });
              wx.setStorage({
                key: "session",
                data: res.data.data.session_key
              });
              success(res.data.data);
            },
            fail: function (e) {
              getOpenID(success);
            },
            complete: function () {
            }
          })
        } else {

        }
      }
    })
  }
}

/**
 * 
 * get请求
 */
function getRequest(url, parameters, success, complete) {
  showLoading();
  wx.request({
    url: url,
    data: parameters,
    method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    header: {
      "Content-Type": "application/json"
    }, // 设置请求的 header
    success: function (res) {
      var jsonString = res.data;
      if (typeof (jsonString) == 'string') {
        jsonString = jsonString.substring(jsonString.indexOf("{"), jsonString.lastIndexOf("}") + 1);
        res.data = JSON.parse(jsonString);
      }
      success(res);
    },
    fail: function (e) { },
    complete: function (e) {
      hideToast();
      complete(e);
    },
  })
}
/**
 * 
 * post请求
 */
function postRequest(url, parameters, success, fail, complete, flag = false) {
  if (flag == false) {
    showLoading();
  } else{
    // wx.hideToast();
  }
  wx.request({
    url: url,
    data: parameters,
    method: "POST", // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    header: {
      "Content-Type": "application/x-www-form-urlencoded"
    }, // 设置请求的 header
    success: function (res) {
      var jsonString = res.data;
      if (typeof (jsonString) == 'string') {
        jsonString = jsonString.substring(jsonString.indexOf("{"), jsonString.lastIndexOf("}") + 1);
        res.data = JSON.parse(jsonString);
      }
      success(res.data);
    },
    fail: function (e) {
      fail(e);
    },
    complete: function (e) {
      hideToast();
      complete(e);
    }
  })
}

/**
 * 
 * 收集模板信息
 */
function collectRequest(url, parameters, success) {
  wx.request({
    url: url,
    data: parameters,
    method: "POST", // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    header: {
      "Content-Type": "application/x-www-form-urlencoded"
    }, // 设置请求的 header
    success: function (res) {
      var jsonString = res.data;
      if (typeof (jsonString) == 'string') {
        jsonString = jsonString.substring(jsonString.indexOf("{"), jsonString.lastIndexOf("}") + 1);
        res.data = JSON.parse(jsonString);
      }
      success(res.data);
    }
  })
}
/**
 加载提示
 */
function showLoading() {
  wx.showToast({
    title: '加载中....',
    icon: 'loading',
    duration: 50000
  });
}
/*
关闭加载
*/
function hideToast() {
  wx.hideToast();
}
/**
 防止重复点击
 */
function waiton() {
  console.log()
  // var that = this;
  // that.setData({
  //   isDisabled: true
  // })
  // setTimeout(() => {
  //   that.setData({
  //     isDisabled: false
  //   })
  // }, 3000);
}
var app = getApp()

function getUserInfo(cb) {
  wx.login({
    success: function (res) {
      if (res.code) {
        var par = {
          code: res.code
        };
        wx.request({
          url: 'https://ceshi.cadhx.com/api/apiregister/get_openid',
          data: par,
          method: "POST", // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
          header: {
            "Content-Type": "application/x-www-form-urlencoded"
          }, // 设置请求的 
          success: function (shuju) {
            var jsonString = shuju.data.data;
            if (typeof (jsonString) == 'string') {
              jsonString = jsonString.substring(jsonString.indexOf("{"), jsonString.lastIndexOf("}") + 1);
              shuju.data.data = JSON.parse(jsonString);
            }
            wx.setStorage({
              key: "openid",
              data: shuju.data.data.openid
            });
            wx.setStorage({
              key: "session",
              data: shuju.data.data.session_key
            });
            //获取身份信息
            wx.getSetting({
              success: function (res) {
                if (res.authSetting['scope.userInfo']) {
                  wx.getUserInfo({
                    success: function (ress) {
                      app.nickName = ress.userInfo.nickName;
                      app.headimgurl = ress.userInfo.avatarUrl;
                      //授权成功
                      //这个是后台创建个人信息,只请求一次
                      var user = wx.getStorageSync('user');
                      var parameters = {
                        encryptedData: ress.encryptedData,
                        iv: ress.iv,
                        openid: shuju.data.data.openid,
                        sessionKey: shuju.data.data.session_key
                      };
                      wx.request({
                        url: 'https://ceshi.cadhx.com/api/apiregister/index',
                        data: parameters,
                        method: "POST", // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
                        header: {
                          "Content-Type": "application/x-www-form-urlencoded"
                        }, // 设置请求的 header
                        success: function (success) {
                          console.log(success)
                          var jsonString = success.data;
                          if (typeof (jsonString) == 'string') {
                            jsonString = jsonString.substring(jsonString.indexOf("{"), jsonString.lastIndexOf("}") + 1);
                            success.data = JSON.parse(jsonString);
                          }
                          if (success.code == 200) {
                            wx.setStorage({
                              key: "user",
                              data: "ok"
                            });
                          }
                          //  typeof cb == "function" && cb(d)
                        },
                        fail: function (e) { },
                        complete: function (e) {
                          var data = {
                            openid: shuju.data.data.openid,
                            session_key: shuju.data.data.session_key
                          }
                          typeof cb == "function" && cb(data)
                        }
                      })

                      //  这个是掉用数据
                    },
                    fail(e) {
                      wx.navigateTo({
                        url: '/pages/login/login',
                      });
                      //授权失败
                      // typeof cb == "function" && cb(data)
                    }
                  })
                }
              }
            })
          },
          fail(e) {
          }
        })
      }
    },
    fail: function (e) {
    }
  })
}

function upDateShareInfo(shareTicket, parameters) {
  //兼容处理e.shareTickets[0]

  if (!wx.openBluetoothAdapter) {
    return;
  }

  wx.login({
    success: function (res) {
      if (res.code) {
        var par = {
          code: res.code
        };
        wx.request({
          url: 'https://ceshi.cadhx.com/api/apiregister/get_openid',
          data: par,
          method: "POST", // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
          header: {
            "Content-Type": "application/x-www-form-urlencoded"
          }, // 设置请求的 
          success: function (e) {
            wx.setStorage({
              key: "openid",
              data: e.data.data.openid
            });
            wx.setStorage({
              key: "session",
              data: e.data.data.session_key
            });
            var parmars = '';
            wx.getShareInfo({
              shareTicket: shareTicket,
              success: function (res) {
                parmars = {
                  encryptedData: res.encryptedData,
                  iv: res.iv,
                  contro: parameters.contro,
                  func: parameters.func,
                  id: parameters.id,
                  openid: e.data.data.openid,
                  sessionKey: e.data.data.session_key,
                  sharekey: parameters.sharekey
                };
                share_request(parmars);
              },
              fail: function (e) { }
            })
          }
        })
      }
    }
  })
}

function hiddenShare() {
  if (wx.openBluetoothAdapter) {
    wx.hideShareMenu()
  }
}
//弹窗
function showModal(title, content, color, success) {
  wx.showModal({
    title: title,
    content: content,
    showCancel: false,
    confirmColor: color ? color : '#222',
    success: success,
  })
}
//弹窗2
function showModal2( content, success) {
  wx.showModal({
    content: content,
    showCancel: false,
    success: success,
  })
}